//
//  UICategory.swift
//  SitPosition
//
//  Created by apple on 2018/12/31.
//  Copyright © 2018 apple. All rights reserved.
//

import Foundation
import UIKit


extension UIView {
    
    static func colored(_ color: UIColor?) -> UIView {
        let v: UIView = UIView()
        v.backgroundColor = color
        return v
    }
    
    func addSubviews(_ views: [UIView]) {
        for v in views {
            addSubview(v)
        }
    }
}


extension UIButton {
    
    /**
     * 设置标题相对于Image的位置
     */
    enum TitleAlignType {
        case left       // 标题在左边、图标在右边
        case bottom     // 标题在底部、图标在顶部
    }
    
    /**
     * 使用场景：
     * 标题在左边、图标在右边
     * 标题在底部、图标在顶部
     */
    func setTitleAlign(with type: TitleAlignType, margin: CGFloat = 0) {
        layoutIfNeeded()
        
        let titleFrame: CGRect = titleLabel?.frame ?? CGRect.zero
        let imageFrame: CGRect = imageView?.frame ?? CGRect.zero
        
        let space: CGFloat = titleFrame.origin.x - imageFrame.origin.x - imageFrame.size.width + margin
        
        switch type {
        case .left:
            imageEdgeInsets = UIEdgeInsets(top: 0, left: titleFrame.size.width+space,
                                           bottom: 0, right: -(titleFrame.size.width + space))
            titleEdgeInsets = UIEdgeInsets(top: 0, left: -(titleFrame.origin.x - imageFrame.origin.x),
                                           bottom: 0, right: titleFrame.origin.x - imageFrame.origin.x)
        case .bottom:
            imageEdgeInsets = UIEdgeInsets(top: 0, left: 0,
                                           bottom: titleFrame.size.height + space,
                                           right: -(titleFrame.size.width))
            titleEdgeInsets = UIEdgeInsets(top: imageFrame.size.height + space,
                                           left: -(imageFrame.size.width),
                                           bottom: 0, right: 0)
        }
    }
}
